package com.example.piece.ui.activity

import android.graphics.Color
import android.os.Bundle
import android.view.*
import androidx.recyclerview.widget.RecyclerView
import com.example.base.aop.click.RepeatClick
import com.example.base.ext.getViewModel
import com.example.base.ext.navigationTo
import com.example.base.ext.toast
import com.example.base.tools.ConfigTool
import com.example.base.ui.activity.BaseActivity
import com.example.base.ui.view.DividerItemDecoration
import com.example.base.vm.onError
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.constant.RoutePath
import com.example.piece.databinding.ActivityLoginBinding
import com.example.piece.entity.HomeTypeInfoEntity
import com.example.piece.ui.adapter.HomeTypeAdapter
import com.example.piece.vm.LoginViewModel
import com.kongzue.dialogx.DialogX
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.PopTip
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.kongzue.dialogx.style.MaterialStyle
import com.therouter.router.Route
import me.samlss.broccoli.Broccoli

@Suppress("UNUSED_PARAMETER")
@Route(path = RoutePath.MAIN_LOGIN)
class LoginActivity : BaseActivity<ActivityLoginBinding>() {

    override val isTransparentStatusBar: Boolean = true

    override val isDarkMode: Boolean = true

    override fun getContentRes(): Int = R.layout.activity_login

    var mBroccoli: Broccoli? = null

    /**  类型 Adapter  **/
    private val homeTypeAdapter: HomeTypeAdapter by lazy {
        val adapter = HomeTypeAdapter(emptyList())
        mBinding.rv.adapter = adapter
        adapter
    }


    override fun initData(savedInstanceState: Bundle?) {

      /*  val m: WindowManager = windowManager
        val d: Display = m.getDefaultDisplay() // 为获取屏幕宽、高

        val p: WindowManager.LayoutParams = window.attributes // 获取对话框当前的参值

        p.height = ((d.getHeight() * 0.7).toInt()) // 高度设置为屏幕的1.0

        p.width = ((d.getWidth() * 1.0).toInt()) // 宽度设置为屏幕的0.8

        p.alpha = 1.0f // 设置本身透明度

        p.dimAmount = 0.8f // 设置黑暗度

        window.attributes = p // 设置生效

        window.setGravity(Gravity.BOTTOM) // 设置靠右对齐
//设置window属性(本例在onCreate函数中设置)
//触摸Dialog外区域时，外区域view接收触摸事件
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
//触摸Dialog外区域时通知Dialog触摸事件
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
*/



        mBinding.data = this.viewModel
        mBinding.rv.addItemDecoration(
            DividerItemDecoration(
                this,
                RecyclerView.HORIZONTAL,
                10,
                Color.parseColor("#ffffff")

            )
        )
        mBinding.rv.adapter = homeTypeAdapter

        homeTypeAdapter.onItemClickChooseFunction { entity, position ->
            homeTypeAdapterItemClick(entity)
        }

        var data = mutableListOf<HomeTypeInfoEntity>()
        data.add(HomeTypeInfoEntity("日志异常", "日志异常"))
        data.add(HomeTypeInfoEntity("PopuWindows", "popuWindows"))
        data.add(HomeTypeInfoEntity("Dialog", "Dialog"))
        data.add(HomeTypeInfoEntity("日志上报", "日志上报"))
        data.add(HomeTypeInfoEntity("轮播图", "轮播图"))
        data.add(HomeTypeInfoEntity("状态栏导航栏", "状态栏导航栏"))
        data.add(HomeTypeInfoEntity("版本更新", "版本更新"))
        data.add(HomeTypeInfoEntity("3D选择器", "3D选择器"))
        data.add(HomeTypeInfoEntity("文字自动播放", "文字自动播放"))
        data.add(HomeTypeInfoEntity("WebSocket", "WebSocket"))
        data.add(HomeTypeInfoEntity("MQTT", "MQTT"))
        data.add(HomeTypeInfoEntity("TCP测试客户端", "ServerSocket"))
        data.add(HomeTypeInfoEntity("TCP测试服务端", "ServerSocket"))

        data.add(HomeTypeInfoEntity("UDP", "DatagramSocket"))
        data.add(HomeTypeInfoEntity("蓝牙通讯", "蓝牙通讯"))
        data.add(HomeTypeInfoEntity("NFC通讯", "NFC通讯"))
        data.add(HomeTypeInfoEntity("ANR异常检测", "ANR异常检测"))
        data.add(HomeTypeInfoEntity("指纹及图形解锁", "指纹及图形解锁"))



        homeTypeAdapter.setNewData(data)

        restoreUserInfo()
        // processDebugMode()

        /* mBroccoli = Broccoli()
         mBroccoli?.addPlaceholders(
             this, R.id.tvWelcome, R.id.ivSignBg

         )
         mBroccoli?.show()*/
        // DialogX.globalStyle=MIUIStyle.style()
        //DialogX.globalStyle=IOSStyle.style()
        //DialogX.globalStyle=KongzueStyle.style()
        DialogX.globalStyle = MaterialStyle.style()



        MessageDialog.show("标题", "正文内容", "确定")
            .setOkButton(object : OnDialogButtonClickListener<MessageDialog?> {

                override fun onClick(baseDialog: MessageDialog?, v: View?): Boolean {
                    PopTip.show("点击确定按钮")
                    return false
                }
            })
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event?.getAction() == MotionEvent.ACTION_OUTSIDE) {
            //接收到外部触摸事件时执行相应处理逻辑(本例中执行window消失机制)。
            finish();
            return true;
        }
        return super.onTouchEvent(event);
    }
    @RepeatClick
    private fun homeTypeAdapterItemClick(entity: HomeTypeInfoEntity) {
        when (entity.name) {
            "日志异常" -> {
                navigationTo(
                    RoutePath.TESTActivity.LOG_ERROR_TEST_ACTIVITY
                )
            }
            "PopuWindows" -> {
                navigationTo(
                    RoutePath.TESTActivity.POPU_WINDOW_TEST_ACTIVITY
                )
            }
            "Dialog" -> {
                navigationTo(
                    RoutePath.TESTActivity.X_DIALOG_TEST_ACTIVITY
                )
            }
            "日志上报" -> {
                navigationTo(
                    RoutePath.TESTActivity.LOG_TEST_ACTIVITY
                )
            }
            "轮播图" -> {
                navigationTo(
                    RoutePath.TESTActivity.ROTATION_RV_TEST_ACTIVITY
                )
            }
            "状态栏导航栏" -> {
                navigationTo(
                    RoutePath.TESTActivity.STATUS_BAR_UTILS_TEST_ACTIVITY
                )
            }
            "版本更新" -> {
                navigationTo(
                    RoutePath.TESTActivity.UP_DATA_TEST_ACTIVITY
                )
            }
            "3D选择器" -> {
                navigationTo(
                    RoutePath.TESTActivity.SELECTOR_3D_TEST_ACTIVITY
                )
            }
            "文字自动播放" -> {
                navigationTo(
                    RoutePath.TESTActivity.TEXTVIEW_AUTO_PLAY_TEST_ACTIVITY
                )
            }
            "WebSocket" -> {
                navigationTo(
                    RoutePath.TESTActivity.WEB_SOCKET_TEST_ACTIVITY
                )
            }
            "MQTT" -> {
                navigationTo(
                    RoutePath.TESTActivity.MQTT_TEST_ACTIVITY
                )
            }
            "TCP测试客户端" -> {
                navigationTo(
                    RoutePath.TESTActivity.TCP_CLIENT_TEST_ACTIVITY
                )
            }
            "TCP测试服务端" -> {
                navigationTo(
                    RoutePath.TESTActivity.TCP_SERVICE_TEST_ACTIVITY
                )
            }
            "UDP" -> {
                navigationTo(
                    RoutePath.TESTActivity.UDP_TEST_ACTIVITY
                )
            }
            "蓝牙通讯" -> {
                navigationTo(
                    RoutePath.TESTActivity.BLUETOOTH_TEST_ACTIVITY
                )
            }
            "NFC通讯" -> {
                navigationTo(
                    RoutePath.TESTActivity.NFC_TEST_ACTIVITY
                )
            }

            "ANR异常检测" -> {
                navigationTo(
                    RoutePath.TESTActivity.ANR_TEST_ACTIVITY
                )
            }

            "指纹及图形解锁" -> {
                navigationTo(
                    RoutePath.TESTActivity.FINGER_TEST_ACTIVITY
                )
            }


        }
    }

    /**  多击判定的数组  **/
    private val mHits = LongArray(2)

    /* */
    /**  处理 debug 模式  **//*
    private fun processDebugMode() {
        if (BuildConfig.DEBUG) {
            mBinding.tvWelcome.setOnClickListener {
                System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
                mHits[mHits.size - 1] = System.currentTimeMillis()

                //单击时间的间隔，以500毫秒为临界值
                if (mHits[0] >= (System.currentTimeMillis() - 500)) {
                    // 完成三击, 将数组初始化, 为下一次三击做准备
                    mHits.forEachIndexed { index, _ ->
                        mHits[index] = 0
                    }
                    debugServerDialog()
                }
            }
        } else autoLogin()
    }*/

    private val viewModel: LoginViewModel by lazy {
        getViewModel<LoginViewModel>()
    }

    /**  恢复用户信息  **/
    private fun restoreUserInfo() {
        viewModel.username.value = ConfigTool.getString(Key.DataKey.USERNAME)
        viewModel.password.value = ConfigTool.getString(Key.DataKey.PASSWORD)
    }

    /**  自动登陆处理  **/
    private fun autoLogin() {
        // 如果曾经登陆过, 则进行自动登陆
        val isOnceLogin = ConfigTool.isExist(
            Key.DataKey.USERNAME,
            Key.DataKey.PASSWORD
        )

        if (isOnceLogin) loginOnLine()
    }

    /* */
    /**
     * 当点击登陆按钮时
     *//*
    fun onClickLogin(view: View) {
        mBroccoli?.clearAllPlaceholders()
startActivity(Intent(this, SocketActivity::class.java))
        //loginOnLine()

    }*/

    /**  登陆系统  **/
    private fun loginOnLine() {
        viewModel.login(this) {
            // toast(it.msg)
            navigationTo(
                RoutePath.Inspection.MAIN_ACTIVITY, mutableMapOf(
                    Key.DataKey.USER_INFO to it.data.userInfo
                )
            )
            finish()
        } onError {
            toast(it)
        }
    }

    @RepeatClick
    fun onClickTest(view: View) {
        navigationTo(
            RoutePath.TESTActivity.LOG_ERROR_TEST_ACTIVITY
        )
    }

}